import 'package:flutter/material.dart';

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("PageView Demo"),
      ),
      body: PageViewDemo(),
    );
  }
}

//PageView
//scrollDirection : 滚动方向, 垂直或者水平, 默认是水平方向
//PageView 是没有缓存功能的, 每次互动到时重新创建, 滑出会销毁
// ListView和GridView 都是通过该 ViewPort的 cacheExtent 预加载和渲染的

//allowImplicitScrolling: 通过下面 PageView 的 Viewport的源码可以知道, 设置allowImplicitScrolling为true, 是一种缓存方案, 但这种方案只能缓存 当前页的前一页和后一页
//继续往后滑时,依然会销毁其他已创建的页面;
/*
viewportBuilder: (BuildContext context, ViewportOffset position) {
          return Viewport(
            // TODO(dnfield): we should provide a way to set cacheExtent
            // independent of implicit scrolling:
            // https://github.com/flutter/flutter/issues/45632
            cacheExtent: widget.allowImplicitScrolling ? 1.0 : 0.0,
            cacheExtentStyle: CacheExtentStyle.viewport,
            axisDirection: axisDirection,
            offset: position,
            clipBehavior: widget.clipBehavior,
            slivers: <Widget>[
              SliverFillViewport(
                viewportFraction: widget.controller.viewportFraction,
                delegate: widget.childrenDelegate,
                padEnds: widget.padEnds,
              ),
            ],
          );
        },
*/

// 可滚动组件子项缓存 KeepAlive,  AutomaticKeepAlive 什么时候会将列表项的 keepAlive 标记为 true 或 false,答案是开发者说了算.
//Flutter 提供了一个 AutomaticKeepAliveClientMixin ，我们只需要让 PageState 混入这个 mixin

//插件 KeepAliveWrapper, 

class PageViewDemo extends StatelessWidget {
  List<Page> children = [
    Page(text: "text : 1"),
    Page(text: "text : 2"),
    Page(text: "text : 3"),
    Page(text: "text : 4"),
    Page(text: "text : 5"),
  ];

  @override
  Widget build(BuildContext context) {
    return PageView(
      // scrollDirection: Axis.vertical,
      allowImplicitScrolling: true,
      children: children,
    );
  }
}

class Page extends StatefulWidget {
  const Page({Key? key, required this.text}) : super(key: key);
  final String text;
  @override
  State<StatefulWidget> createState() => _PageState();
}

class _PageState extends State<Page> with AutomaticKeepAliveClientMixin {
  @override
  Widget build(BuildContext context) {
    print("build ${widget.text}");
    super.build(context);
    return Center(child: Text("${widget.text}", textScaleFactor: 5));
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
